import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:time/test/test_file.dart';

class WebFileApp extends StatelessWidget {
  const WebFileApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "文件",
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const FilePage(),
    );
  }
}

class FilePage extends StatefulWidget {
  const FilePage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return FilePageState();
  }
}

class FilePageState extends State<StatefulWidget> {
  var filePath = "";
  var fileInfo = "";
  var fileContent = "";

  FilePageState() {
//    initFilePath();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("文件")),
      body: Column(
        children: [
          MaterialButton(
              color: Colors.indigo,
              child: const Text(
                "选择文件",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () => selectFile()),
          Text(filePath),
          Text(fileInfo),
          MaterialButton(
              color: Colors.indigo,
              child: const Text(
                "文件信息",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () => showFileInfo()),
          MaterialButton(
              color: Colors.indigo,
              child: const Text(
                "创建文件",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () => createFile()),
          MaterialButton(
              color: Colors.indigo,
              child: const Text(
                "删除文件",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () => deleteFile()),
          MaterialButton(
              color: Colors.indigo,
              child: const Text(
                "写文件",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () => writeFile()),
          MaterialButton(
              color: Colors.indigo,
              child: const Text(
                "添加内容",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () => writeFileAccess()),
          MaterialButton(
              color: Colors.indigo,
              child: const Text(
                "读文件",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () => readFile()),
          Text(fileContent)
        ],
      ),
    );
  }

  showFileInfo() async {
    var file = File(filePath);
    file.exists().then((value) {
      fileInfo = ("exist:" + value.toString());
      updateFileInfo();
      if (value) {
        file.length().then((value) {
          fileInfo += ",大小:" + value.toString();
          setState(() {
            fileInfo;
          });
        });
      }
    });
  }

  updateFileInfo() {
    setState(() {
      fileInfo;
    });
  }

  /// 获取存储权限
  selectFile() async {
    var filePickerResult = await FilePicker.platform.pickFiles();
    if (filePickerResult != null && filePickerResult.count > 0) {
      for (var element in filePickerResult.files) {
        print("文件:" + element.name + " \t 大小:" + element.size.toString());
      }
    }
  }

  void initFilePath() {
    TestFile().getPath().then((value) {
      setState(() {
        filePath = value + "/test.json";
        if (Platform.isMacOS) {
          filePath = "~/test.json";
        }
      });
    }).onError((error, stackTrace) {
      print("onError:2");
      if (Platform.isMacOS) {
        filePath = "~/test.json";
      }
    }).catchError((any) {
      print("catchError:" + Platform.isMacOS.toString());
      if (Platform.isMacOS) {
        filePath = "~/test.json";
      }
    });
  }

  createFile() {
    var file = File(filePath);
    file.exists().then((value) {
      if (!value) {
        file.create().then((value) {
          showFileInfo();
          readFile();
        });
      }
    });
  }

  deleteFile() async {
    var file = File(filePath);
    await file.delete();
    showFileInfo();
  }

  writeFile() async {
    var file = File(filePath);
    await file.writeAsString("Hello World!\n");
    showFileInfo();
    readFile();
  }

  writeFileAccess() async {
    var file = File(filePath);
    var ioSink = file.openWrite(mode: FileMode.append);
    ioSink.write(DateTime.now().millisecondsSinceEpoch.toString() +
        "Hello World! (添加内容) \n");
    ioSink.flush();
    showFileInfo();
    readFile();
  }

  readFile() async {
    var file = File(filePath);
    var s = await file.readAsString();
    setState(() {
      fileContent = s;
    });
  }
}
